import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';

class ImagesPage extends StatefulWidget {
  const ImagesPage({super.key});

  @override
  State<ImagesPage> createState() => _ImagesPageState();
}

class _ImagesPageState extends State<ImagesPage> {
  final _imagePicker = ImagePicker();
  final List<XFile> _imageFile = [XFile('assets/images/2.jpeg')];
  List<String> _selectedImagePaths = [];

  Future<void> _pickImages() async {
    final images = await _imagePicker.pickMultiImage();
    setState(() {
      _imageFile.addAll(images);
      _selectedImagePaths.addAll(images.map((e) => e.path));
      _saveSelectedImages(_selectedImagePaths);
    });
  }

  Future<void> _saveSelectedImages(List<String> images) async {
    final prefs = await SharedPreferences.getInstance();
    String imagePaths = images.join(',');
    prefs.setString('selectedImages', imagePaths);
  }

  Future<List<String>> _loadSelectedImages() async {
    final prefs = await SharedPreferences.getInstance();
    final imagePathString = prefs.getString('selectedImages');
    if (imagePathString != null) {
      return imagePathString.split(',').toList();
    } else {
      return ["assets/images/2.jpeg"];
    }
  }

  @override
  void initState() {
    super.initState();
    _loadSelectedImages().then((images) {
      setState(() {
        _selectedImagePaths = images;
        _imageFile.addAll(images.map((e) => XFile(e)));
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('图片'),
        ),
        body: SafeArea(
            child: Column(
          children: [
            Expanded(
                child: GridView.builder(
                    gridDelegate:
                        const SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 4),
                    itemCount: _imageFile!.length,
                    itemBuilder: (context, index) {
                      if (index == 0) {
                        return GestureDetector(
                            onTap: _pickImages,
                            child: Container(
                              color: const Color.fromRGBO(238, 238, 238, 1),
                              child: const Center(
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Icon(Icons.add),
                                    Text('添加照片'),
                                  ],
                                ),
                              ),
                            ));
                      }
                      return Image.file(
                        File(_imageFile![index]!.path),
                        fit: BoxFit.cover,
                      );
                    }))
          ],
        )));
  }
}
